<template>
  <div id="pictureDetailPage">
    <!--一行两列展示图片信息（栅格布局）-->
    <!--行-->
    <a-row :gutter="[16, 16]">

      <!--第一列： 图片预览 -->
      <a-col :sm="24" :md="16" :xl="18">
        <a-card title="图片预览">
          <a-image
            :src="picture.url"
            style="max-height: 600px;
            object-fit: contain" />
        </a-card>
      </a-col>

      <!--第二列： 图片信息区域 -->
      <a-col :sm="24" :md="8" :xl="6">
        <a-card title="图片信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="作者">
              <a-space>
                <a-avatar :size="24" :src="picture.user?.userAvatar" />
                <div>{{ picture.user?.userName }}</div>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="名称">
              {{ picture.name ?? '未命名' }}
            </a-descriptions-item>
            <a-descriptions-item label="简介">
              {{ picture.introduction ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类">
              {{ picture.category ?? '默认' }}
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in picture.tags" :key="tag">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">
              {{ picture.picFormat ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽度">
              {{ picture.picWidth ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="高度">
              {{ picture.picHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">
              {{ picture.picScale ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ formatSize(picture.picSize) }}
            </a-descriptions-item>
          </a-descriptions>

          <!-- 图片操作 -->
          <a-space wrap>
            <a-button type="primary" @click="doDownload">
              免费下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>

            <a-button :icon="h(ShareAltOutlined)" type="primary" ghost @click="doShare">
              分享
            </a-button>

            <a-button v-if="canEdit" :icon="h(EditOutlined)" type="default" @click="doEdit">
              编辑
            </a-button>

            <a-popconfirm
              danger
              title="确认删除该条数据?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete"
            >
            <a-button v-if="canDelete" :icon="h(DeleteOutlined)" danger>
              删除
            </a-button>
            </a-popconfirm>

          </a-space>
        </a-card>
      </a-col>
    </a-row>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<!--js脚本-->
<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue'
import {
  deletePictureUsingPost, downloadPictureUsingPost,
  getPictureVoByIdUsingGet,
  updateShareExpireTimeUsingPost
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { DeleteOutlined, DownloadOutlined, EditOutlined,ShareAltOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { useRouter } from 'vue-router'
import { downloadImage, formatSize } from '@/utils'
import ShareModal from '@/components/ShareModal.vue'
import { SPACE_PERMISSION_ENUM } from '@/constants/space.ts'

// 定义属性,拿到图片id
interface Props {
  id: string | number
}
const props = defineProps<Props>()

//定义图片对象
const picture = ref<API.PictureVO>({})

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (picture.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
      router.replace('/')
    }
  } catch (e: any) {
    message.error('获取图片详情失败：' + e.message)
    router.replace('/')
  }
}
// 钩子函数，初次加载页面时获取到图片数据
onMounted(() => {
  fetchPictureDetail()
})

//定义一个实例路由
const router = useRouter()

// 编辑图片函数（跳转）
const doEdit = () => {
  const spaceId = picture.value.spaceId;
  if (!spaceId) {
    router.push('/add_picture?id=' + picture.value.id)
  }else {
    router.push('/add_picture?id=' + picture.value.id+'&spaceId=' + picture.value.spaceId)
  }
}

// 删除图片的函数
const doDelete = async () => {
  const id = picture.value.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
  } else {
    message.error('删除失败')
  }
  router.push('/')
}
//全局变量-当前登录用户
const loginUser = useLoginUserStore().loginUser

// 下载图片的函数
const doDownload = async () => {
  const spaceId = picture.value.spaceId as number;
  if (spaceId != null) {
    downloadImage(picture.value.url)
  }else {
    const id = picture.value.id
    if (!id) {
      return
    }
    // 使用类型断言确保 downloadCount 是 number 类型
    const downloadCount = loginUser.downloadCount as number;
    if (downloadCount >= 1) {
      await downloadPictureUsingPost({ id })
      window.location.reload();
    }else {
      message.error("您今日的下载次数已用完！可以升级vip身份提高下载次数");
    }
  }
}

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = () => {
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.value.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
  //更新过期时间
  updateShareExpireTime();
}

// 更新图片的分享过期时间
const updateShareExpireTime = async () => {
  const id = picture.value.id
  if (!id) {
    return
  }
  const res = await updateShareExpireTimeUsingPost({ id })
  if (res.data.code === 0) {
    if (picture.value.spaceId){
      message.success('分享链接已更新，5分钟内有效')
    }else {
      message.success('分享成功')
    }
  } else {
    message.error('分享链接操作失败！请重试或联系管理员')
  }
}


</script>
<!--css样式-->
<style scoped>
#pictureDetailPage {
  margin-bottom: 16px;
}
</style>
